#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, socket, string, time, ssl, os, commands, time, datetime, ConfigParser
from types import *
#from time import time
import sysinfo, quote, weather, forecast

#Settings
config = ConfigParser.SafeConfigParser({'ircserver':'None','ircport':'None','nick':'horribot','realname':'horribot','chan':'#None','owner':'*!*@*','ownernick':'*','serverpass':None})
config.read('settings.ini')

ircserver = config.get('General','ircserver')
ircport = config.getint('General','ircport')
usessl =config.get('General','ssl')
ident =config.get('General','ident')
nick =config.get('General','nick')
realname =config.get('General','realname')
chan = config.get('General','chan')
owner = config.get('General','owner')
ownernick = config.get('General','ownernick')
serverpass = config.get('General','serverpass')

if ircserver == "None":
	print "Please configure the bot in settings.ini"
	exit()

readbuffer =""

if usessl == "true":
	ssocket = socket.socket()
	# require ssl from the server
	s = ssl.wrap_socket(ssocket)
else:
	s = socket.socket()

s.connect((ircserver,  ircport))

if serverpass != None: 
	s.send("PASS %s\r\n" % serverpass)

s.send("NICK %s\r\n" % nick)
s.send("USER %s %s bla :%s\r\n" % (ident, ircserver, realname))

futime = time.time()-10
tildetime = time.time()-2
quotetime = time.time()-2
addquotetime = time.time()-2
wtime = time.time()-2

while 1:
	readbuffer=readbuffer+s.recv(1024)
	temp=string.split(readbuffer, "\n")
	readbuffer=temp.pop( )

	for line in temp:
		line=string.rstrip(line)
		line=string.split(line)

		# Output to text to command line
		print line

		# Respond to the irc server's pings
		if line[0] == "PING":
			s.send("PONG %s\r\n" % line[1])
		elif line[1] == "JOIN" or line[1] == "PART" or line[1] == "NICK" or line[1] == "QUIT":
			null = 0 #this gets rid of an error
		elif "messages/announcements" in line:
			s.send("PRIVMSG %s :Hi Boss\n" % ownernick)
			# s.send("JOIN %s\r\n" % chan)

		elif line[3] == ":!pybot":
			if line[0] == owner and line[4] == "end":
				s.send("PRIVMSG %s :Quitting.\n" % line[2])
				s.send("QUIT :horribot\n")
				exit()
			if line[0] == owner:
				s.send("PRIVMSG %s :Waiting for your command master.\n" % line[2])
			else:
				s.send("PRIVMSG %s :Can I help you?\n" % line[2])
		elif line[3] == ":!%s"%nick or line[3] ==":.%s"%nick:
				s.send("PRIVMSG %s :Available Commands: ~ .w .fc .quote !addquote .addquote !fu !time .%s !%s \n" % (line[2], nick, nick))
		elif line[3] == ':.uptime':
			s.send("PRIVMSG %s :%s\n"%(line[2],  os.popen("uptime").readlines()[0]))

		elif line[0] == owner and line[3] == ":!cpuinfo":
			s.send("PRIVMSG %s :%s\n"%(line[2], sysinfo.cpuinfo()))

		elif line[0] == owner and line[3] == ":!sysinfo":
			s.send("PRIVMSG %s :%s\n"%(line[2], sysinfo.sys()))

		elif line[0] == owner and line[3] == ":!bw":
			s.send("PRIVMSG %s :%s\n"%(line[2], sysinfo.bw()))

		elif line[0] == owner and line[3] == ":!du":
			s.send("PRIVMSG %s :%s\n"%(line[2], sysinfo.disk()))

		elif line[0] == owner and line[3] == ":!join":
			s.send("JOIN %s\r\n" % line[4])
			s.send("PRIVMSG %s :Joining %s\n"%(line[2], line[4]))
				
		elif line[0] == owner and line[3] == ":!part":
			s.send("PRIVMSG %s :Parting %s\n"%(line[2], line[4]))
			s.send("PART %s \r\n" % line[4])
		elif line[0] == owner and line[3] == ":!nick":
			s.send("NICK %s\r\n" % line[4])
			nick = line[4]
		elif line[0] == owner and line[3] == ":!nick":
			s.send("MODE %s %s\r\n" % (nick,line[4]))
		elif line[0] == owner and line[3] == ":!msg":
			longmessage = ""
			for message in line[5::]:
				longmessage += message 
				longmessage += " "
			s.send("PRIVMSG %s :%s\n" % (line[4],longmessage))
		
		elif line[0] == owner and line[3] == ":!cycle":
			s.send("PART %s\r\n" % line[2])
			s.send("JOIN %s\r\n" % line[2])
		
		elif line[3] == ":~":
			if tildetime+2 <= time.time() and line[2] != nick:
				s.send("PRIVMSG %s ~\n" % line[2])
				tildetime = time.time()+2
		
		elif line[3] == ":.quote":
			
			if quotetime+1 <= time.time() and line[2] != nick:
				quotetime = time.time()+2
			
			if len(line) >= 5:
			
				try:
					s.send("PRIVMSG %s :%s\n" %(line[2], quote.printquote(int(line[4]))))
				except ValueError:
	
					try:
						s.send("PRIVMSG %s :%s\n" %(line[2], quote.searchquote(line[4])))
					except ValueError:
						s.send("PRIVMSG %s :Quote could not be found\n" % line[2])
	
			else:
				s.send("PRIVMSG %s :%s\n" %(line[2], quote.printrandomquote()))
		
		elif line[3] == ":.w":
			if wtime+2 <= time.time() and line[2] != nick:
				wtime = time.time()+2
			if len(line) > 4:
				longw = ""
				for linew in line[4::]:
					#print linew
					longw += linew 
					longw += " "
	
				currently = weather.weather(longw)
				s.send("PRIVMSG %s :%s \n" %(line[2],currently))
	
			else:
				s.send("PRIVMSG %s :To check current weather please use .w <location>\n" %(line[2]))
		elif line[3] == ":.fc":
			if len(line) > 4:
				longw = ""
				for linew in line[4::]:
					print linew
					longw += linew 
					longw += " "
		
				fc = forecast.weather(longw)
				s.send("PRIVMSG %s :%s \n" %(line[2],fc[0]))
				s.send("PRIVMSG %s :%s \n" %(line[2],fc[1]))
	
			else:
				s.send("PRIVMSG %s :To check current weather please use .fc <location>\n" %(line[2]))
	
		elif line[3] == ":!addquote" or line[3] == ":.addquote":
			if addquotetime+2 <= time.time() and line[2] != nick:
				addquotetime = time.time()+2
			if len(line) > 4:
				longquote = ""
				for linequote in line[4::]:
					longquote += linequote 
					longquote += " "
					
				if len(longquote) < 10:
					s.send("PRIVMSG %s :Quote not long enough.\n" % line[2])
				else:
					number = quote.addquote(longquote)
				s.send("PRIVMSG %s :Quote %s Added\n" %(line[2],number))
	
			else:
				s.send("PRIVMSG %s :To add a quote please use !addquote <quote>\n" %(line[2]))
		
		elif line[3] == ":!fu":
			if futime+60 <= time.time():
			
				s.send("PRIVMSG %s :................/´¯/) \n" % line[2]) 
				s.send("PRIVMSG %s :............../¯..// \n" % line[2])
				s.send("PRIVMSG %s :............./..../ / \n" % line[2])
				s.send("PRIVMSG %s :......../´¯/'...'/´¯¯`·¸ \n" % line[2])
				s.send("PRIVMSG %s :...../'/.../..../......./¨¯\ \n" % line[2])
				s.send("PRIVMSG %s :...('(...´(..´......,~/'...') \n" % line[2])
				s.send("PRIVMSG %s :....\.................\/..../ \n" % line[2])
				s.send("PRIVMSG %s :......\.............. _.·´ \n" % line[2])
				s.send("PRIVMSG %s :.......\..............( \n" % line[2])
				s.send("PRIVMSG %s :........\.............\ \n" % line[2])
				futime = time.time()
			else:
				s.send("PRIVMSG %s :You must wait 60 seconds between uses of this command\n" % line[2])
	
		elif line[3] == ":!time":
			s.send("PRIVMSG %s :%s\n" % (line[2],time.strftime("%a %m.%d.%y | %l.%M.%S %p (GMT %z)")))
